from system.models import SysUser, SysMenu, SysRole, SysUserRole, SysConfig, SysOperLog, CoreModel
from rest_framework import serializers
from django.contrib.auth.hashers import make_password
from typing import override
import json


# 基本序列化
class CoreSerializer(serializers.ModelSerializer):    
    """
    CoreModel的序列化器，用于序列化和反序列化CoreModel模型的数据。
    """
    id = serializers.IntegerField(required=False)  # 让id变成非必填
    create_time = serializers.DateTimeField(read_only=True)
    update_time = serializers.DateTimeField(read_only=True)
    creator = serializers.CharField(source='creator.username', read_only=True)
    updater = serializers.CharField(source='updater.username', read_only=True)
    description = serializers.CharField(required=False)

    class Meta:
        model = CoreModel
        fields = ['id', 'create_time', 'update_time', 'creator', 'updater', 'description']
        read_only_fields = ['create_time', 'update_time', 'creator', 'updater', 'description']
    

# 用户表序列化
class SysUserSerializer(serializers.ModelSerializer):
    id = serializers.IntegerField(required=False)  # 让id变成非必填
    username = serializers.CharField(required=False) 
    roleList = serializers.SerializerMethodField()
    
    class Meta:
        model = SysUser
        fields = ['id', 'username', 'nick_name', 'password', 'email', 'avatar', 'phonenumber', 'last_login', 
                 'create_time', 'update_time', 'remark', 'is_active', 'is_staff', 'user_from', 'roleList']
        read_only_fields = ['create_time', 'date_joined', 'is_staff', 'is_superuser']
        extra_kwargs = {
            'password': {'write_only': True}
        }

    def get_roleList(self, obj):
        roles = SysUserRole.objects.filter(user=obj)
        return [{'id': r.role.id, 'name': r.role.name} for r in roles]
        
    def create(self, validated_data):
        # 创建用户时跳过id参数
        validated_data.pop('id', None)
        password = validated_data.pop('password', 'YGreTh59cIPN')
        user = SysUser(**validated_data)
        user.password = make_password(password)  # 使用Django的密码加密方法
        user.save()
        return user
        
    def update(self, instance, validated_data):
        # 更新用户时跳过id参数和用户名
        validated_data.pop('id', None)
        validated_data.pop('username', None)
        password = validated_data.pop('password', None)
        
        for attr, value in validated_data.items():
            setattr(instance, attr, value)
            
        if password is not None:
            instance.password = make_password(password)  # 更新密码时使用Django的密码加密方法
            
        instance.save()
        return instance


class SysMenuSerializer(serializers.ModelSerializer):
    """菜单序列化器，支持多级菜单结构"""
    children = serializers.SerializerMethodField()

    def get_children(self, obj):
        if hasattr(obj, "children") and obj.children:
            return SysMenuNestedSerializer(obj.children, many=True).data
        return []

    class Meta:
        model = SysMenu
        fields = '__all__'

# 嵌套菜单序列化器，支持任意层级的菜单
class SysMenuNestedSerializer(serializers.ModelSerializer):
    children = serializers.SerializerMethodField()
    
    def get_children(self, obj):
        if hasattr(obj, "children") and obj.children:
            return SysMenuNestedSerializer(obj.children, many=True).data
        return []
    
    class Meta:
        model = SysMenu
        fields = '__all__'


class SysRoleSerializer(serializers.ModelSerializer):
    class Meta:
        model = SysRole
        fields = '__all__'


class SysUserRoleSerializer(serializers.ModelSerializer):
    class Meta:
        model = SysUserRole
        fields = '__all__'
        
class SysRoleMenuSerializer(serializers.Serializer):
    menuIdList = serializers.ListField(child=serializers.IntegerField())

    class Meta:
        field = ('menuIdList',)

    @override
    def to_representation(self, instance):
        # 处理查询集(QuerySet)的情况
        if hasattr(instance, 'all'):
            return {'menuIdList': [item.menu_id for item in instance]}
        # 处理列表的情况
        elif isinstance(instance, list):
            return {'menuIdList': [item.menu_id for item in instance]}
        # 处理单个对象的情况
        else:
            return {'menuIdList': [instance.menu_id]}
            
# class SysRoleMenuSerializer(serializers.ModelSerializer):
#     class Meta:
#         model = SysRoleMenu
#         fields = '__all__'

# 批量删除角色的序列化器
class BatchDeleteSerializer(serializers.Serializer):
    """批量删除角色的请求数据结构"""
    ids = serializers.ListField(
        child=serializers.IntegerField(),
        help_text="角色ID列表"
    )
    
    
# 分配角色菜单的序列化器
class GrantMenuSerializer(serializers.Serializer):
    """为角色分配菜单的请求数据结构"""
    role_id = serializers.IntegerField(help_text="角色ID")
    menuIds = serializers.ListField(
        child=serializers.IntegerField(),
        help_text="菜单ID列表"
    )
    
    
# 通用响应序列化器
class MessageResponseSerializer(serializers.Serializer):
    """通用消息响应结构"""
    msg = serializers.CharField(help_text="响应消息")


# 配置表序列化
class SysConfigSerializer(serializers.ModelSerializer):    
    class Meta:
        model = SysConfig
        fields = '__all__'



###############  Audit LOG ###############
class SysOperLogSerializer(serializers.ModelSerializer):
    class Meta:
        model = SysOperLog
        fields = '__all__'